<?php
namespace Xxfaxy\UserBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Xxfaxy\UserBundle\Entity\User;
use Xxfaxy\UserBundle\Form\UserType;
use Xxfaxy\DryBundle\Form\Type\SubmitGroupForNewType;
use Xxfaxy\DryBundle\Form\Type\SubmitGroupForEditType;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class UserController extends Controller
{
    public function indexAction()
    {
        $twigData = array();
        $function = $this->get('service.common.function');
        $twigData['enabledArray'] = $function->getChoice('status');
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('XxfaxyUserBundle:User')->findAll();
        $twigData['users'] = $users;
        return $this->render('XxfaxyUserBundle:user:index.html.twig', $twigData);
    }

    public function newAction(Request $request)
    {
        $user = new User();
        $form = $this->createForm('Xxfaxy\UserBundle\Form\UserType', $user);
        $form->add('SubmitGroup', SubmitGroupForNewType::class, array('label' => ' ', 'label_attr' => array('class' => 'control-label col-sm-2'), 'attr' => array('class' => 'form-control'), 'mapped' => false));
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()){
            $function = $this->get('service.common.function');
            $encoder = $this->get('security.password_encoder');
            $post = $request->request->all();
            $formData = $function->getFormData($post);
            $password = $encoder->encodePassword($user, $formData['password']);
            $user->setPassword($password);
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
            $this->addFlash('message_success', $function->translation('operationSuccess'));
            $post = $function->getFormData($request->request->all());
            $SubmitGroup = $post['SubmitGroup'];
            if(isset($SubmitGroup['submit'])){
                return $this->redirectToRoute('user_new');
            }
            else if(isset($SubmitGroup['submitAndShow'])){
                return $this->redirectToRoute('user_show', array('id' => $user->getId()));
            }
            else if(isset($SubmitGroup['submitAndList'])){
                return $this->redirectToRoute('user_index');
            }
            else if(isset($SubmitGroup['submitAndEdit'])){
                return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
            }
        }
        return $this->render('XxfaxyUserBundle:user:new.html.twig', array(
            'user' => $user,
            'form' => $form->createView(),
        ));
    }

    public function showAction(User $user)
    {
        $twigData = array();
        $function = $this->get('service.common.function');
        $twigData['enabledArray'] = $function->getChoice('status');
        $twigData['user'] = $user;
        return $this->render('XxfaxyUserBundle:user:show.html.twig', $twigData);
    }

    public function editAction(Request $request, User $user)
    {
        $editForm = $this->createForm('Xxfaxy\UserBundle\Form\UserType', $user);
        $editForm->add('SubmitGroup', SubmitGroupForEditType::class, array('label' => ' ', 'label_attr' => array('class' => 'control-label col-sm-2'), 'attr' => array('class' => 'form-control'), 'mapped' => false));
        $editForm->handleRequest($request);
        if($editForm->isSubmitted() && $editForm->isValid()){
            $function = $this->get('service.common.function');
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
            $this->addFlash('message_success', $function->translation('operationSuccess'));
            $post = $function->getFormData($request->request->all());
            $SubmitGroup = $post['SubmitGroup'];
            if(isset($SubmitGroup['submit'])){
                return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
            }
            else if(isset($SubmitGroup['submitAndShow'])){
                return $this->redirectToRoute('user_show', array('id' => $user->getId()));
            }
            else if(isset($SubmitGroup['submitAndList'])){
                return $this->redirectToRoute('user_index');
            }
            else if(isset($SubmitGroup['submitAndNew'])){
                return $this->redirectToRoute('user_new');
            }
        }
        return $this->render('XxfaxyUserBundle:user:edit.html.twig', array(
            'user' => $user,
            'edit_form' => $editForm->createView(),
        ));
    }

    public function deleteAction(Request $request, User $user)
    {
        $form = $this->createDeleteForm($user);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()){
            $em = $this->getDoctrine()->getManager();
            $em->remove($user);
            $em->flush();
        }
        return $this->redirectToRoute('user_index');
    }

    private function createDeleteForm(User $user)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('user_delete', array('id' => $user->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    public function updatePasswordAction(Request $request)
    {
        if($request->request->has('oldPassword')){
            $oldPassword = $request->request->get('oldPassword');
            $newPassword = $request->request->get('newPassword');
            $newRePassword = $request->request->get('newRePassword');
            $user = $this->get('security.token_storage')->getToken()->getUser();
            $encoder = $this->get('security.password_encoder');
            $function = $this->get('service.common.function');
            if(strlen($oldPassword) >= 9 && strlen($newPassword) >= 9 && $newPassword == $newRePassword && $encoder->isPasswordValid($user, $oldPassword)){
                $em = $this->getDoctrine()->getManager();
                $password = $encoder->encodePassword($user, $newPassword);
                $user->setPassword($password);
                $em->flush();
                $this->addFlash('message_success', $function->translation('operationSuccess'));
            }
            else{
                $this->addFlash('message_error', $function->translation('operationFail'));
            }
            return $this->redirectToRoute('user_update_password');
        }
        return $this->render('XxfaxyUserBundle:user:updatePassword.html.twig');
    }

    public function loginAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('XxfaxyUserBundle:User')->find($id);
        if(! $user){
            throw new UsernameNotFoundException('User not found');
        }
        else{
            $token = new UsernamePasswordToken($user, null, 'your_firewall_name', $user->getRoles());
            $this->get('security.context')->setToken($token);
            $event = new InteractiveLoginEvent($request, $token);
            $this->get('event_dispatcher')->dispatch('security.interactive_login', $event);
        }
        return $this->redirectToRoute('user_update_password');
    }

}
